import paho.mqtt.client as mqtt
import time # To add delay
import RPi.GPIO as GPIO
import json

# 水泵针口
watering_channel = 27
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)

# 人工开关

# MQTT服务器设置
MQTT_BROKER = "broker.emqx.io"  # 例如: "broker.hivemq.com"
MQTT_PORT = 1883  # MQTT默认端口
MQTT_TOPIC = "watering/Water"  # 你要发布的MQTT主题
MQTT_CLIENT_ID = "mqttx_c7c21cc9"  # MQTT客户端ID

# 当服务器响应的时候，会回调这个函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    # 订阅主题
    client.subscribe("watering/Water")

# 回调函数，当收到消息时，触发该函数
def on_message(client, userdata, msg):
    print(f"Received message: Topic - {msg.topic}, Payload - {msg.payload.decode()}")
    data = json.loads(msg.payload.decode())
    if data["command"] == "start":
        GPIO.output(watering_channel, GPIO.LOW)  # 水泵开启
        print("Watering started")
    elif data["command"] == "stop":
        GPIO.output(watering_channel, GPIO.HIGH)  # 水泵关闭
        print("Watering stopped")



# MQTT客户端
client = mqtt.Client(MQTT_CLIENT_ID)
client.on_connect = on_connect
client.on_message = on_message

# 设置遗嘱消息（立遗嘱），当树莓派断电，或者网络出现异常中断时，发送遗嘱消息往这个 topic
client.will_set('watering/testament', b'{"status": "Off"}')
# 创建连接，三个参数分别为 broker 地址，broker 端口号，保活时间 broker.emqx.io 是免费的mqtt服务器，如果是自己搭建的服务器需要填上自己的ip地址
#当服务器响应的时候 会回调 on_connect 方法

client.connect(MQTT_BROKER, MQTT_PORT, 60)
# 设置网络循环堵塞，在调用 disconnect() 或程序崩溃前，不会主动结束程序
client.loop_start()

# 设置针口为输出模式
GPIO.setup(watering_channel, GPIO.OUT)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.output(watering_channel, GPIO.HIGH)  # 程序结束时确保水泵关闭
    GPIO.cleanup()
